import { getToken, refreshAccessToken } from '@/utils/token'
import { useAccountStore } from '@/stores/account';
import { usePermissionStore } from '@/stores/permission'

const baseTitle = import.meta.env.VITE_APP_TITLE;

const WHITE_LIST = ['/login', '/forbidden', '/404', '/oauth'];

export function createPageLoadingGuard(router) {
    router.beforeEach(() => {
        window.$loadingBar?.start()
    })

    router.afterEach(() => {
        setTimeout(() => {
            window.$loadingBar?.finish()
        }, 200)
    })

    router.onError(() => {
        window.$loadingBar?.error()
    })
}

export function createPageTitleGuard(router) {
    router.afterEach((to) => {
        const pageTitle = to.meta?.title;
        
        if (pageTitle) {
            document.title = `${pageTitle} | ${baseTitle}`
        } else {
            document.title = baseTitle
        }
    })
}

export function createPermissionGuard(router) {

    const account = useAccountStore();
    const permission = usePermissionStore();

    router.beforeEach(async (to, from, next) => {
        if (WHITE_LIST.includes(to.path)) {
            next();
            return;
        }

        const token = getToken();

        if (token) {
            // 已经登录了，就不让再去登录页面了
            if (to.path === '/login') {
                next({ path: '/' });
                return;
            }

            refreshAccessToken();

            // 已经拿到用户信息
            if (account.id) {
                if (permission.check(to, account))
                    next();
                else
                    next({ path: '/forbidden' });

                return;
            }

            // 没有用户信息，则获取授权
            try {
                await account.getAccountInfo();
            } catch (error) {
                account.logout();
            }

            next({ ...to, replace: true });
        } else {
            next({ path: '/login' });
        }
    })
}

export function setupRouterGuard(router) {
    createPageLoadingGuard(router)
    createPageTitleGuard(router)
    createPermissionGuard(router)
}